package com.offcn.bigdata.spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

/**
 * spark的入门案例：
 *    程序的入口：SparkContext
 *      在SparkCore中
 *          java的入口是JavaSparkContext
 *          scala的入口SparkContext
 *      在SparkSQL中
 *          SQLContext
 *          HiveContext
 *                  2.x之后统一为SparkSession
 *      在SparkStreaming中
 *          java的入口是JavaStreamingContext
 *          scala的入口StreamingContext
 *     以上程序入口的构建都得需要依赖SparkConf对象
 *
 * 编程步骤：
 *  1. 创建SparkContext对象
 *      需要依赖SparkConf
 *          需要相应的配置？
 *              A master URL must be set in your configuration
 *              An application name must be set in your configuration
 *  2. 通过SparkContext来加载外部数据，得到编程模型RDD
 *  3. 根据业务需要对RDD进行转换transformation操作
 *  4. 得需要action操作来触发spark作业的执行
 *  5. 释放资源
 */
public class JavaSparkWordCountApp {
    public static void main(String[] args) {
        //step 1
        SparkConf conf = new SparkConf();
        conf.setMaster("local[*]");
        conf.setAppName(JavaSparkWordCountApp.class.getSimpleName());

        JavaSparkContext jsc = new JavaSparkContext(conf);

        //step 2 加载数据
        JavaRDD<String> lines = jsc.textFile("E:/data/spark/hello.txt");
        System.out.println("partition: " + lines.getNumPartitions());
        //step 3 transformation变换操作
        JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String line) throws Exception {
                String[] words = line.split("\\s+");
                return Arrays.asList(words).iterator();
            }
        });

        JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String word) throws Exception {
                return new Tuple2<String, Integer>(word, 1);
            }
        });

        JavaPairRDD<String, Integer> ret = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });

        // step 4 action触发作业
        ret.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            @Override
            public void call(Tuple2<String, Integer> t) throws Exception {
                System.out.println(t._1 + "---" + t._2);
            }
        });

        //step 5
        jsc.close();
    }
}
